package kr.co.happenstance;

import java.util.Arrays;
import java.util.List;

import com.facebook.Session;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionState;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class LoginActivity extends BaseActivity implements View.OnClickListener{
	protected final String TAG = "<<<LoginActivity>>>";
	
	private boolean bProgressLogin = false;
	
	
	/**
	 * Facebook 연동을 위한 Bundle객체<br><br>
	 * 
	 * onCreate(Bundle savedInstanceState)에선 받은 Bundle객체를 저장해둠
	 * 
	 */
	private Bundle savedInstanceState = null;
	
	/**
	 * Facebook 연동을 위한 SessionStatusCallback 객체
	 */
	private Session.StatusCallback statusCallback = new SessionStatusCallback();	
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);		
		
		addActivity(this);
	}	

	@Override
	public void onClick(View view) {
		switch(view.getId()){
			case R.id.btn_facebook_login:
				Log.d(TAG, "btn_facebook_login Click............");
				bProgressLogin = true;
				Session session = Session.getActiveSession();
				if(session == null){
					if(savedInstanceState != null){
						session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
					}
					if(session == null){
						session = new Session(this);
					}
					Session.setActiveSession(session);
					session.addCallback(statusCallback);
					if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)){
						session.openForRead(
							new Session.OpenRequest(this)
							.setCallback(statusCallback)
							.setDefaultAudience(SessionDefaultAudience.FRIENDS)
						);
					}
				}
				checkFacebookLogin();				
				break;
		}
	}
	
	@Override
	public void onStart(){
		super.onStart();
		if(Session.getActiveSession() != null){
			Session.getActiveSession().addCallback(statusCallback);
		}
	}
	
	@Override
	public void onStop() {
		super.onStop();
		if(Session.getActiveSession() != null){
			Session.getActiveSession().removeCallback(statusCallback);
		}    
	}	
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		boolean processed = false;
		if(Session.getActiveSession() != null){
			processed = Session.getActiveSession().onActivityResult(this, requestCode,resultCode, data);
		}
		Log.d(TAG, "processed["+processed+"]");

	}		
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if(Session.getActiveSession() != null){
			Session session = Session.getActiveSession();
			Session.saveSession(session, outState);
		}
	}	

	/**
	 * 페이스북 로그인 체크 메소드<br><br>
	 * 
	 * 로그인전 일때는 페이스북 로그인창 호출 해서 로그인 수행<br>
	 * 로그인후 일때는 페이스북 권한 체크 해서 해당 권한이 없을 경우 권한부여 창을 호출 해서 권한 요청
	 * 로그인/권한 체크 모두 정상일때 다시 IntroActivtiy 호출
	 * 
	 * 
	 */
	private void checkFacebookLogin(){
		Session session = Session.getActiveSession();
		if(session != null && bProgressLogin){
			boolean logined = session.isOpened();
			if(logined){
				
				String accessToken = session.getAccessToken();
				Log.d(TAG, "accessToken["+accessToken+"]");
				Log.d(TAG, "=================>["+session.getPermissions()+"]");
				if(!session.getPermissions().contains("user_birthday")){
					String[] PERMISSION_ARRAY_READ = {"user_birthday"};
					List<String> PERMISSION_LIST=Arrays.asList(PERMISSION_ARRAY_READ);
					session.requestNewReadPermissions(new Session.NewPermissionsRequest(LoginActivity.this, PERMISSION_LIST));
					
				}else{
					//email, user_birthday 권한 취득 되어 있으면 다시 intro 시작
					Intent intent = new Intent(LoginActivity.this, IntroActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					LoginActivity.this.finish();				
					
				}
				
			}else{
				// log in 시도
				if(!session.isOpened() && !session.isClosed()){
					session.openForRead(new Session.OpenRequest(this)
					.setCallback(statusCallback)
					.setDefaultAudience(SessionDefaultAudience.FRIENDS));
				}else{
					Session.openActiveSession(this, true, statusCallback);
				}
			}
			
		}
	}	
	
	/**
	 * 페이스북 로그인 Session의 상태값을 받는 콜백 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private class SessionStatusCallback implements Session.StatusCallback {

		@Override
		public void call(Session session, SessionState state, Exception exception) {
			Log.d(TAG, "SessionStatusCallback call................["+state+"]");
			
			if(state == SessionState.OPENED  || state == SessionState.OPENED_TOKEN_UPDATED){
				//로그인
				checkFacebookLogin();
				
			}else if (state == SessionState.CLOSED){
				//로그아웃
				
			}else if (state == SessionState.CLOSED_LOGIN_FAILED){
				// 여러 이유로 인증실패.
				bProgressLogin = false;
				
			}
			
			
		}
		
	}		
}
